#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
import re
import os 
# path="/Users/b612/Desktop/kuru开发文档/B6C/python_test/MakeScript.1/NodeFile/Script.lua"
# word1 = "begin"
# word2 = "ended"

# #文本所在路径，引号前加r指按路径处理
# #关键字word1,word2,换关键字，需修改引号间的内容

# class match2Words(object):
#     lines=0
#     def __init__(self,path,word1,word2):
#         self.path = path
#         self.word1 = word1
#         self.word2 = word2
#     def key_match(self):
#         with open(self.path,'r') as f:
#             buffser = f.read()
#             buffser= buffser.replace('\n','')
#             pattern = re.compile(self.word1+'(.*?)'+self.word2,re.S)
#             result = pattern.findall(buffser)
#             if result != []:
#                 print(result)
#                 #self.lines +=1
#                 #print("匹配到的行数：",self.lines)
#             else:
#                 print("没有找到你输入的关键字")


# matchWords = match2Words(path, word1, word2)
# matchWords.key_match()

#
# 获取require 的起点终点行号
#
def getRequireContent(path):
    start = 0
    end = 0

    requirecontent = ""
    currentline = 0
    commonFile = open(path, "r+")
    for (num, value) in enumerate(commonFile):
        # print ("line num is: ",num,"content:",value)
        if value.find("require") != -1:
            if start == 0:
                start = num+1
            requirecontent = requirecontent+value
            currentline = num+1
    end = currentline
    commonFile.close()

    return start-1, end

#
# 获取require 的起点终点行号
#


def getEndLine(path):
    end = 0

    currentline = 0
    commonFile = open(path, "r+")
    for (num, value) in enumerate(commonFile):
        currentline = num+1
    end = currentline
    commonFile.close()

    return end

#
# 获取某段字符串 特定子串出现次数
#


def word_count_in_str(string, keyword):
    return len(string.split(keyword))-1

#
# 获取function字段出现次数
#


def getFunctionCount(path):
    commonFile = open(path, "r+")
    content = commonFile.read()
    count = (word_count_in_str(content, 'function'))

    commonFile.close()
    return count

# 获取参数的起点终点（require 和第一个function的行号）


def getParamContent(path, index):
    functioncount = 0
    requirecontent = ""
    currentline = 0
    commonFile = open(
        path, "r+")

    for (num, value) in enumerate(commonFile, 0):
        # print ("line num is: ",num,"content:",value)
        if value.find("function") != -1:
            requirecontent = requirecontent+value
            currentline = num+1
            functioncount = functioncount+1
            if index == functioncount:
                break

    commonFile.close()
    return currentline-1


def loadDataSet(path, start, end):
    f = open(path, "r")
    content = ""
    for line in f.readlines()[start:end]:
        content = content+line
    return content
    f.close()

# 返回两个标签之间的内容


def key_match(path):
    symbol = "function"
    endsymbol = "end   "
    lines = 0
    with open(path, 'r') as f:
        buffser = f.read()
        # buffser = buffser.replace('\n', '')
        pattern = re.compile(symbol+'(.*?)'+endsymbol, re.S)
        result = pattern.findall(buffser)
        if result != []:
            # print(result)
            return str(result[0])
            #self.lines +=1
            # print("匹配到的行数：",self.lines)
        else:
            print("没有找到你输入的关键字")

# 切片法
def reverse1(content):
    s = content
    return s[::-1]


def getEndSymbolLine(path, content, line):
    path=path.split("index.lua")[0]+"ss.lua"
    f=open(path,"w")
    
    content=reverse1(content)
    f.write(content)
    f.close()
    f=open(path,"r")
    pos=0
    for (num, value) in enumerate(f):
        if value.find("dne") != -1:     
            print(num)
            pos=int(num)
            break
       
    f.close()        
    os.remove(path)
    return pos
if __name__ == "__main__":
    path = "/Users/b612/Desktop/kuru开发文档/Product/开发需求/19.02/08.眨眼换妆/306463_2_plain/script1/index.lua"

    requireStart = 0
    requireEnd = 0

    paramStart = 0
    paramEnd = 0

    requireStart, requireEnd = getRequireContent(path)
    print(requireStart, requireEnd)

    functionCount = getFunctionCount(path)
    print(functionCount)
    if functionCount > 2:
        pass
    else:
        paramStart = requireEnd
        paramEnd = getParamContent(path, 1)
        initStart = paramEnd+1

        initEnd = getParamContent(path, 2)

        frameStart = initEnd+1
        frameEnd = getEndLine(path)-1

        initEnd=initEnd-(getEndSymbolLine(path, str(loadDataSet(path, 1, initEnd)), initStart))
        # print(frameEnd)
        requireContent = loadDataSet(path, requireStart, requireEnd)
        paramContent = loadDataSet(path, paramStart, paramEnd)
        initContent = loadDataSet(path, initStart, initEnd)
        frameContent = loadDataSet(path, frameStart, frameEnd)
        print(frameContent)
